package com.my.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.reggie.common.CustomException;
import com.my.reggie.common.RabbitmqDelayProducer;
import com.my.reggie.config.DelayMessageConfig;
import com.my.reggie.enums.wxpay.WxRefundStatus;
import com.my.reggie.enums.wxpay.WxTradeState;
import com.my.reggie.mapper.OrdersMapper;
import com.my.reggie.pojo.*;
import com.my.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Resource
    private RabbitmqDelayProducer delayProducer;
    /**
     * 提交订单
     * @param orders
     * @param session
     */
    @Override
    @Transactional
    public Orders createOrder(Orders orders, HttpSession session) {
        //获取当前用户信息
        Long userId = (Long) session.getAttribute("user");
        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //获取当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> SCLqw = new LambdaQueryWrapper<>();
        SCLqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(SCLqw);
        //生成订单号
        long orderId = IdWorker.getId();
        //设置订单号
        orders.setNumber(String.valueOf(orderId));
        //设置订单状态(待付款)
        orders.setStatus(1);
        //设置下单用户id
        orders.setUserId(userId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置付款时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置实收金额
        AtomicInteger amount = new AtomicInteger(0);
        for(ShoppingCart shoppingCart : shoppingCartList) {
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(100)).multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
        }
        orders.setAmount(BigDecimal.valueOf(amount.get()));
        //设置用户信息
        User user = userService.getById(userId);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        //保存单条订单信息
        this.save(orders);

        //设置订单详细信息
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for(ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            AtomicInteger detailAmount = new AtomicInteger(0);
            detailAmount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetail.setAmount(BigDecimal.valueOf(detailAmount.get()));
            orderDetailList.add(orderDetail);
        }
        //批量保存订单详细数据
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车数据
        shoppingCartService.remove(SCLqw);

        //设置延迟队列，过期时间为5分钟
        log.info("订单编号：{}进入延迟队列...",orders.getNumber());
        delayProducer.publish(orders.getNumber(),String.valueOf(orders.getId()),
                DelayMessageConfig.DELAY_EXCHANGE_NAME,DelayMessageConfig.ROUTING_KEY_ORDER,1000*60*5);

        return orders;
    }

    /**
     * 根据订单号更新订单状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatusByOrderNo(String id, String status) {
        log.info("更新订单状态===>{}",status);

        LambdaUpdateWrapper<Orders> luw = new LambdaUpdateWrapper<>();
        luw.eq(Orders::getNumber,id);

        Orders order = new Orders();
        if(WxTradeState.SUCCESS.getType().equals(status)) {
            order.setStatus(2);  //已付款
        }
        else if(WxTradeState.NOTPAY.getType().equals(status)) {
            order.setStatus(1); //未支付
        }
        else if(WxTradeState.CLOSED.getType().equals(status)) {
            order.setStatus(5); //已取消
        }
        else if(WxRefundStatus.PROCESSING.getType().equals(status)) {
            order.setStatus(6); //退款中
        }
        else if("REFUND_SUCCESS".equals(status)) {
            order.setStatus(7); //退款成功
        }
        else if(WxRefundStatus.ABNORMAL.getType().equals(status)) {
            order.setStatus(8); //退款异常
        }
        else {
            int new_status = Integer.parseInt(status);
            order.setStatus(new_status);
        }
        this.update(order,luw);
    }

    /**
     * 根据订单号获取订单状态
     * @param orderNumber
     * @return
     */
    @Override
    public Integer getOrderStatus(String orderNumber) {
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getNumber,orderNumber);
        Orders order = this.getOne(lqw);
        if(order == null) {
            return null;
        }
        return order.getStatus();
    }

    /**
     * 查询超过5分钟未支付的订单
     * @param minutes
     * @return
     */
    @Override
    public List<Orders> getNoPayOrderOvertime(int minutes) {
        //获取minutes分钟之前的时间
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //未付款
        lqw.eq(Orders::getStatus,1);
        //时间超时
        lqw.le(Orders::getOrderTime,instant);
        return this.list(lqw);
    }

    /**
     * 查询退款处理超过5分钟的订单
     * @param minutes
     * @return
     */
    @Override
    public List<Orders> getProcessingOvertime(int minutes) {
        //获取minutes分钟之前的时间
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //退款处理中 or 退款处理异常
        lqw.in(Orders::getStatus,6,8);
        //超过minutes分钟
        lqw.le(Orders::getRefundTime,instant);

        return this.list(lqw);
    }
}
